<template>
    <div>
        <div>
            <el-config-provider :locale="zhCn"> <!--《:locale="zhCn 》设置语言-->

                <el-scrollbar height="70vh">
                    <!-- 出差申请 -->
                    <el-row :gutter="24">
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
                                <el-form-item label="出差申请" label-position="top"
                                    :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                                    <div class="progress-bar">
                                        <div class="progress"></div>
                                    </div>
                                </el-form-item>

                            </div>
                        </el-col>

                        <!--  -->
                        <el-col :span="12">
                            <!-- {{ businessTripsData }} -->
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="出差单号"
                                    label-position="top">
                                    <el-input placeholder="自动生成无需填写" style="width: 354px;" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="申请日期"
                                    label-position="top">
                                    <el-input placeholder="" :value="businessTripsData.applicationDate"
                                        style="/*width: 260px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="姓名" label-position="top">
                                    <el-input placeholder="" :value="user.employeeName" style="/*width: 354px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="所在部门"
                                    label-position="top">
                                    <el-input placeholder="" :value="user.department.deptName" style="/*width: 260px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="出差目的地"
                                    label-position="top" required>
                                    <el-cascader v-model="selectedRegion" :options="regionData" placeholder="请选择地址"
                                        style="width: 354px" clearable :teleport="true" />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="出差开始日期"
                                    label-position="top" required>
                                    <el-date-picker v-model="businessTripsData.startDate" style="width: 354px;"
                                        type="date" placeholder="" value-format="YYYY-MM-DD" :size="size"
                                        :disabled-date="disabledDate" />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="出差结束日期"
                                    label-position="top" required>
                                    <el-date-picker v-model="businessTripsData.endDate" style="width: 354px;"
                                        type="date" placeholder="" value-format="YYYY-MM-DD" :size="size"
                                        :disabled-date="disabledDate" />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="预计出差天数"
                                    label-position="top">
                                    <el-input placeholder="" :value="businessTripDays" style="/*width: 260px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="出差事由" label-position="top"
                                    required>
                                    <el-input v-model="businessTripsData.reason" style="width: 633px;" :rows="6"
                                        type="textarea" placeholder="" />
                                </el-form-item>
                            </div>
                        </el-col>

                        <div class="bottom-submit-bar">
                            <el-button type="primary" @click="onSubmit">提交</el-button>
                        </div>

                    </el-row>
                </el-scrollbar>

            </el-config-provider>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, defineEmits } from 'vue'
import { regionData, codeToText } from 'element-china-area-data'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router';
import request from '@/api/request';

let emits = defineEmits(['ref-table']);

// 获取session中的用户信息 - 需要解析JSON字符串
let user = JSON.parse(sessionStorage.getItem('user') || '{}');

const businessTripsData = ref({});

const businessTripDays = ref(0);

const selectedRegion = ref([])

const textArray = computed(() => {
    return selectedRegion.value.map(code => {
        // 查找对应的文字，如果找不到则显示"未知地区"
        return codeToText[code] || '未知地区';
    });
});

// 拼接成完整地址
const fullAddress = computed(() => {
    return textArray.value.join('-');
});

const disabledDate = (time) => {
    // 禁用今天之前的日期（不包括今天）
    return time.getTime() < new Date(new Date().setHours(0, 0, 0, 0));
};

watch(() => selectedRegion.value, (newValue) => {
    if (newValue) {
        console.log(fullAddress.value)
        businessTripsData.value.destination = fullAddress.value;
    }
})

// 监听开始日期和结束日期的变化
watch(
    () => [businessTripsData.value.startDate, businessTripsData.value.endDate],
    ([newStart, newEnd]) => {
        // 确保两个日期都存在
        if (newStart && newEnd) {
            // 转换为Date对象
            const start = new Date(newStart);
            const end = new Date(newEnd);

            // 确保日期有效且结束日期不早于开始日期
            if (!isNaN(start.getTime()) && !isNaN(end.getTime()) && end >= start) {
                // 计算毫秒差并转换为天数（1天 = 86400000毫秒）
                const timeDiff = end - start;
                const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
                businessTripDays.value = dayDiff;
            } else {
                businessTripDays.value = 0;
                if (end < start) {
                    ElMessage.warning('结束日期不能早于开始日期');
                    businessTripsData.value.endDate = '';
                }
            }
        } else {
            businessTripDays.value = 0;
        }
    },
    { immediate: true } // 初始化时立即执行一次
);

const onSubmit = () => {

    if (!businessTripsData.value.destination) {
        ElMessage.warning('请选择出差目的地');
        return;
    }

    if (!businessTripsData.value.startDate) {
        ElMessage.warning('请选择出差开始日期');
        return;
    }

    if (!businessTripsData.value.endDate) {
        ElMessage.warning('请选择出差结束日期');
        return;
    }

    if (!businessTripsData.value.reason) {
        ElMessage.warning('请填写出差事由');
        return;
    }

    console.log({ ...businessTripsData.value });


    request({
        url: '/businessTrip/insert',
        method: 'post',
        data: { ...businessTripsData.value }
    }).then(res => {
        if (res.code == 200) {
            ElMessage.primary(res.msg);
            emits('ref-table');
        } else {
            ElMessage.warning(res.msg);
        }
    })

}


//日期类型

const isVisible = ref(false)
// 复制添加
const add = () => {
    isVisible.value = true
    router.push('./insert.vue')
}
//修改显示
const EditDisplay = ref(false)
//编辑
const Editor = () => {
    EditDisplay.value = true
}

//删除操作
const open = () => {
    ElMessageBox.confirm(
        '你确定要删除吗?',
        '通知',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            ElMessage({
                type: 'success',
                message: '删除成功',

            })
            emit("ref-table")
        })
        .catch(() => {
            ElMessage({
                type: 'warning',
                message: '取消操作',
            })
        })
}

// 设置当前日期时间
const setCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    //  ${hours}:${minutes}:${seconds}
    businessTripsData.value.applicationDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 组件挂载时设置当前日期时间
onMounted(() => {
    setCurrentDateTime();
})

</script>

<style scoped>
/* 外层容器，可控制整体条的高度、圆角等 */
.progress-bar {
    height: 6px;
    background-color: #ccebf7;
    border-radius: 3px;
    display: flex;
    width: 100%;
    /* 确保进度条容器宽度占满父容器 */
    overflow: hidden;
    /* 防止子元素溢出 */
}

.progress {
    width: 8%;
    height: 10;
    background-color: #61c3ea;
    border-radius: 3px 0 0 3px;
    transition: width 0.3s ease;
    /* 添加宽度变化的过渡效果 */
}

.bottom-submit-bar {
    /* position: fixed; */
    /* 固定定位 */
    bottom: 0;
    /* 靠底部 */
    left: 0;
    width: 100%;
    background-color: #fff;
    /* 背景色，可根据需求调整 */
    border-top: 1px solid #eaeaea;
    /* 顶部边框，与页面区分 */
    padding: 12px 24px;
    /* 内边距，适配截图里的间距风格 */
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    /* 按钮靠左，可根据实际需求调整 */
    z-index: 10;
    /* 提高层级，避免被其他内容覆盖 */
}
</style>